package com.atguign.gulimall.order.web;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguign.gulimall.order.config.pay.AliPayConfig;
import com.atguign.gulimall.order.entity.OrderEntity;
import com.atguign.gulimall.order.service.OrderService;
import com.atguign.gulimall.order.service.PaymentInfoService;
import com.atguign.gulimall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;


@Controller
@Slf4j
public class AliPayController {
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "json";
    private static final String CHARSET = "UTF-8";
    private static final String SIGN_TYPE = "RSA2";    //签名方式
    @Resource
    private AliPayConfig aliPayConfig;
    @Resource
    private OrderService orderService;
    @Resource
    private PaymentInfoService paymentInfoService;
    @ResponseBody
    @GetMapping(value = "/payOrder", produces = "text/html;charset=UTF-8")
    public String pay(@RequestParam("orderSn") String orderSn) throws Exception {
        OrderEntity orderByOrderSn = orderService.getOrderByOrderSn(orderSn);
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(), aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        model.setTotalAmount(orderByOrderSn.getPayAmount().setScale(2, RoundingMode.HALF_UP).toString());//订单金额
        model.setOutTradeNo(orderSn);                                                                             //设置商户订单号
        model.setSubject("test");                                                                                 //订单名称
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        model.setTimeoutExpress("9m");
        request.setBizModel(model);


        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            log.error(e.toString());
        }
        return form;
    }
    /**
     * 功能：支付宝服务器异步通知页面
     * 日期：2017-03-30
     * 说明：
     * 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
     * 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。


     *************************页面功能说明*************************
     * 创建该页面文件时，请留心该页面文件中无任何HTML代码及空格。
     * 该页面不能在本机电脑测试，请到服务器上做测试。请确保外部可以访问该页面。
     * 如果没有收到该页面返回的 success
     * 建议该页面只做支付成功的业务逻辑处理，退款的处理请以调用退款查询接口的结果为准。
     */
    @ResponseBody
    @PostMapping(value = "/payed/notify")
    public String payed(PayAsyncVo vo, HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
            // 支付宝验签
            if (checkSignature) {
               String result =  orderService.hadlePayResult(vo);
            }
        }
        return "success";
    }
}
